//
//  IG_GameGamesViewController.m
//  iGameApp
//
//  Created by Yf66 on 16/1/16.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IG_GameGamesViewController.h"
#import "IGRightTabBarController.h"
#import "IGCustomNavigationController.h"
#import "IG_GameHotTableViewCell.h"
#import "IGWillBeginTableViewCell.h"
#import "IGGameStateView.h"
#import "IG_GameHotModel.h"
#import "IGLivePlayer.h"
#import "IG_RoundDetailViewController.h"
@interface IG_GameGamesViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) IGCustomNavigationController *navC;
@property (nonatomic, strong) UIView *tabBarView;
@property (nonatomic, strong) UIButton *backButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) IGGameStateView *stateView;
@property (nonatomic, strong) NSArray *sectionHeadArray;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) IGLivePlayer *player;
@property (nonatomic, strong) AppDelegate *appdelegate;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UIActivityIndicatorView *flower;
@end

@implementation IG_GameGamesViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    _navC = (IGCustomNavigationController *)self.navigationController;
    _navC.bgView.hidden = YES;
    IGRightTabBarController *tabBarController = (IGRightTabBarController *)self.navigationController.parentViewController;
    tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    _navC.bgView.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _appdelegate = [UIApplication sharedApplication].delegate;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    // Do any additional setup after loading the view from its nib.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addCustomTabBarView];
    self.view.backgroundColor = [UIColor blackColor];
    
    _titleLabel.text = _name;
    // 图片大小 640 * 250
    _headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 250 / 640)];
    _tableView.tableHeaderView = _headImageView;
    [_tableView registerNib:[UINib nibWithNibName:@"IG_GameHotTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_GameHotTableViewCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IGWillBeginTableViewCell" bundle:nil] forCellReuseIdentifier:@"IGWillBeginTableViewCell"];
    _tableView.autoresizesSubviews = NO;
    _tableView.sectionHeaderHeight = 45;
    
    _listArray = [NSMutableArray array];
    _sectionHeadArray = [NSArray array];
    [self requestDataWithStr:_match_stage];
    [self requestData];
}

- (void)requestDataWithStr:(NSString *)str
{
    [_listArray removeAllObjects];
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlStr = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getMatchList?match_stage=%@&num=65535&start=0&tournament_id=%@",str,_tournament_id];
    [IGAFNetworking requestWithUrlString:urlStr parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
            // NSLog(@"%@",dataDic);
        if (![dataDic[@"message"] isEqualToString:@"成功"]) {
            return;
        }
        for (NSDictionary *dic in dataDic[@"data"][@"match"]) {
            IG_GameHotModel *model = [[IG_GameHotModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_listArray addObject:model];
        }
        if (_listArray.count == 0) {
            _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }
        [_tableView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
}

- (void)requestData
{
    _match_stage = [_match_stage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *imageUrlStr = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getTournamentImg?match_stage=%@&tournament_id=%@",_match_stage,_tournament_id];
    [IGAFNetworking requestWithUrlString:imageUrlStr parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        NSLog(@"%@",dataDic);
        if (![dataDic[@"message"] isEqualToString:@"成功"]) {
            return;
        }
        [_headImageView sd_setImageWithURL:[NSURL URLWithString:dataDic[@"data"][@"app_tournament_image"]] placeholderImage:nil];
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
    
    [IGAFNetworking requestWithUrlString:[NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getMatchStageList?tournament_id=%@",_tournament_id] parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        if (![dataDic[@"message"] isEqualToString:@"成功"]) {
            return;
        }
        _sectionHeadArray = dataDic[@"data"];
        [self addSectionView];
        [_stateView sectionButtonAction:(UIButton *)[_stateView viewWithTag:100]];
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
}

- (void)addCustomTabBarView
{
    _tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    _tabBarView.backgroundColor = [UIColor blackColor];
    _tabBarView.alpha = 0;
    [self.view addSubview:_tabBarView];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth/2-100, 0, 200, 44)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.textColor = [UIColor whiteColor];
    [_tabBarView addSubview:_titleLabel];
    
    _backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _backButton.frame = CGRectMake(10, 20, 50, 44);
    [_backButton setTitle:@"返回" forState:(UIControlStateNormal)];
    [_backButton addTarget:self action:@selector(backButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_backButton];
}

- (void)backButtonAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- UITableView 代理和数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        IGWillBeginTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IGWillBeginTableViewCell" forIndexPath:indexPath];
        cell.gameStateLabel.text = @"精彩比赛";
        _tableView.rowHeight = 30;
        return cell;
    }
    
    IG_GameHotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IG_GameHotTableViewCell" forIndexPath:indexPath];
      IG_GameHotModel *model = _listArray[indexPath.row - 1];
    _tableView.rowHeight = 100;
   
    NSString *state = [NSString stringWithFormat:@"%@",model.match_state];
    if ([state isEqualToString:@"2"]) {
        cell.gameStateLabel.textColor = [UIColor redColor];
        cell.goImage.hidden = NO;
    } else {
        if ([state isEqualToString:@"4"]) {
            cell.goImage.hidden = NO;
        } else {
            cell.goImage.hidden = YES;
        }
        cell.gameStateLabel.textColor = [UIColor blueColor];
    }
  
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 45)];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat rate = _tableView.contentOffset.y / (kScreenWidth * 250 / 640 - 44);
    _tabBarView.alpha = rate;
    _stateView.frame = CGRectMake(0, (kScreenWidth * 250 / 640 + 20) - rate * (kScreenWidth * 250 / 640 - 44), kScreenWidth, 45);
    if (rate > 1) {
        _stateView.frame = CGRectMake(0, 64, kScreenWidth, 45);
    }
}

- (void)addSectionView
{
    _stateView = [[IGGameStateView alloc] initWithFrame:CGRectMake(0, kScreenWidth * 250 / 640 + 20, kScreenWidth, 45)];
    [self.view addSubview:_stateView];
    
    for (int i = 0; i < _sectionHeadArray.count; i++) {
        [_stateView addButtonWithX:kScreenWidth * (i+1)/(_sectionHeadArray.count+1) titleStr:_sectionHeadArray[i][@"match_stage"] withTag:i withCount:_sectionHeadArray.count];
    }
    
    __weak IG_GameGamesViewController *myself = self;
    _stateView.block = ^void(NSInteger index){
        [myself requestDataWithStr:myself.sectionHeadArray[index][@"match_stage"]];
    };
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    IG_GameHotModel *model = _listArray[indexPath.row - 1];
    NSString *str = [NSString stringWithFormat:@"%@",model.match_state];
    NSInteger state = [str integerValue];
    if (state == 2) {
        [self setUpLiveDataWithcate:[NSString stringWithFormat:@"%@",model.cate]];
    } if (state ==  4) {
        IG_RoundDetailViewController *detailVC = [[IG_RoundDetailViewController alloc] init];
        detailVC.vid = [NSString stringWithFormat:@"%@",model.vid];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

//  直播数据请求
- (void)setUpLiveDataWithcate:(NSString *)date {
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"ios"] = @"1";
    NSString *newUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/LiveSourceUrl?cate=%@",date];
    [IGAFNetworking requestWithUrlString:newUrl parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSDictionary *dic = dataDic[@"data"];
        NSString *liveUrl = dic[@"HD"];
        _player = [[IGLivePlayer alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) URL:[NSURL URLWithString:liveUrl]];
        [_appdelegate.window addSubview:_player];
        [self setPlaySubviews];
        [_player addObserver:self forKeyPath:@"vlcPlayer.state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    } error:^(NSError *requestError) {
        NSLog(@"数据请求失败");
    }];
}

#pragma mark -- 播放器设置
//  添加播放器上的子视图
- (void)setPlaySubviews {
    _button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _button.frame = CGRectMake(20, 80, 30, 30);
    [_button setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [_button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_appdelegate.window addSubview:_button];
    [self setScreen];
    
    _flower = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    _flower.frame = CGRectMake((kScreenWidth - 25) / 2, (kScreenHeight - 25) / 2, 25, 25);
    [_appdelegate.window addSubview:_flower];
    [_flower startAnimating];
    
}
- (void)setScreen {
    _button.frame = CGRectMake(kScreenWidth - 60, 40, 30, 30);
    [UIView animateWithDuration:0.1 animations:^{
        _player.frame = CGRectMake(0, 0, kScreenHeight, kScreenWidth);
        _player.center = CGPointMake(kScreenWidth / 2, kScreenHeight / 2);
        
    } completion:^(BOOL finished) {
        _player.transform = CGAffineTransformRotate( _player.transform, M_PI_2);
        _button.transform = CGAffineTransformRotate(_button.transform, M_PI_2);
    }];
}

- (void)buttonClick:(UIButton *)sender {
    [_player removeObserver:self forKeyPath:@"vlcPlayer.state" context:nil];
    [_player.vlcPlayer stop];
    [_player removeFromSuperview];
    [_button removeFromSuperview];
    [_flower removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
